﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;


namespace Meligo.DynamicViewCreator.Helpers
{
    public static class Logger
    {
        // because  it is not possible to log to the ULS log via sandbox, writing a log to a custom list
        public static void WriteToLog(string message, Exception ex)
        {
            SPWeb currentweb = SPContext.Current.Web;
            if (currentweb != null)
            {
                SPList logList = null;

                logList = currentweb.Lists.TryGetList("LoggingList");
                if (logList == null)
                {
                    // log list doesn't exist, creating it
                    Guid listId = currentweb.Lists.Add("Logger", string.Empty, SPListTemplateType.GenericList);
                    logList = currentweb.Lists[listId];
                    SPField newField = logList.Fields.CreateNewField(SPFieldType.Note.ToString(), "StackTrace");
                    logList.Fields.Add(newField);
                    // I Don't want this list to be seen outside of site collection permission
                    logList.BreakRoleInheritance(false);
                }

                SPListItem newItem = logList.Items.Add();
                newItem[SPBuiltInFieldId.Title] = "DynamicViewCreator: " + message;
                newItem["StackTrace"] = ex.StackTrace.ToString();
                newItem.Update();
            }
        }
    }
}
